package com.xzx.config;

import com.xzx.interceptor.LoginInterceptor;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequestEvent;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 *
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/8/18 17:39
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public ServletContextInitializer servletContextInitializer(ApplicationContext applicationContext) {
        return new ServletContextInitializer() {
            @Override
            public void onStartup(ServletContext servletContext) throws ServletException {
                String contextPath = servletContext.getContextPath();
                System.out.println("contextPath: " + contextPath);
                servletContext.setAttribute("ctxPath", contextPath);
            }

        };
     }

     @Bean
     public ErrorAttributes errorAttributes() {
         return new RestErrorAttributes();
     }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("/main");
        registry.addViewController("/main").setViewName("main");
        registry.addViewController("/main.html").setViewName("main");
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/login.html").setViewName("login");
        registry.addViewController("/user/add.html").setViewName("user/add");
        registry.addViewController("/role/add.html").setViewName("role/add");
        registry.addViewController("/permission/add.html").setViewName("permission/add");
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加拦截器
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/login", "/doLogin", "/logout", "/bootstrap/**", "/css/**", "/fonts/**", "/img/**", "/favicon.ico", "/jquery/**", "/script/**", "/ztree/**", "/layer/**");
    }
}
